﻿using CSRedis;
using Microsoft.Extensions.Caching.Redis;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Spark.AspNetCore;
using System;
using Microsoft.Extensions.Caching.Distributed;

namespace Spark.RedisCache
{
    public static class ServiceCollectionExtensions
    {
        /// <summary>
        /// 添加csredis 缓存
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="action"></param>
        /// <see cref="https://github.com/2881099/csredis"/>
        /// <returns></returns>
        public static SparkBuilder AddCsRedisCache(this SparkBuilder builder, Action<RedisOption> action)
        {
            if (action == null)
                throw new ArgumentNullException(nameof(action));
            var option = new RedisOption();
            action?.Invoke(option);

            var redisClient = new CSRedisClient(option.ConnectionString);
            //初始化 RedisHelper
            RedisHelper.Initialization(redisClient);
            var cache = new CSRedisCache(RedisHelper.Instance);
            builder.Services.AddSingleton<IDistributedCache>(cache);
            return builder;
        }

        public static SparkBuilder AddCsRedisCache(this SparkBuilder builder, IConfiguration configuration, string sectionKey = "GlobalConfig:RedisConnectionStrings")
        {
            if (configuration == null)
                throw new ArgumentNullException(nameof(configuration));

            var option = new RedisOption();
            configuration.GetSection(sectionKey).Bind(option);

            var redisClient = new CSRedisClient(option.ConnectionString);
            //初始化 RedisHelper
            RedisHelper.Initialization(redisClient);
            var cache = new CSRedisCache(RedisHelper.Instance);
            builder.Services.AddSingleton<IDistributedCache>(cache);
            return builder;
        }
    }
}